package com.zhuannimei.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.util.LogUtils;
import com.xuxihong1.Dianle;
import com.xuxihong1.GetTotalMoneyListener;
import com.xxhong.znm.offers.OffersManager;
import com.zhuannimei.GlobalApplication;
import com.zhuannimei.R;
import com.zhuannimei.adapter.AppAdapter;
import com.zhuannimei.domain.Product;
import com.zhuannimei.domain.Promotion;
import com.zhuannimei.domain.ZnmList;
import com.zhuannimei.net.RequestServerData;
import com.zhuannimei.parser.PromotionParser;
import com.zhuannimei.utility.AdUtil;
import com.zhuannimei.utility.JpushUtil;
import com.zhuannimei.utility.JsonUtil;
import com.zhuannimei.utility.MessageTypes;
import com.zhuannimei.utility.MessageUtil;
import com.zhuannimei.utility.PersistTool;
import com.zhuannimei.utility.UiUtil;
import com.zhuannimei.utility.WuLog;
import com.zhuannimei.utility.ZnmData;
import com.zhuannimei.utility.ZnmHttpParams;
import com.zhuannimei.view.BubbleView;
import com.zhuannimei.view.CustomIndicator;

import android.R.integer;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class TabOneActivity extends BaseActivity {
	private static final String TAG = "Fragment1";
	// ----------------------------------------------------
	// 滑动图片的集合
	private ViewPager mViewPager;
	private TextView mSlideTitle;
	// ---------------------------------------------------
	private CustomIndicator indicator;

	private ListView mLvApps;
	private List<ZnmList> mAppInfos = getZnmlist();
	private List<Promotion> mPromotions = new ArrayList<Promotion>();
	LayoutInflater lf;

	private BubbleView noticeBubble;

	@Override
	protected void handleMsg(Message msg) {
		super.handleMsg(msg);
		switch (msg.what) {
		case MessageTypes.UPDATE_MESSAGE_NOTICE:
			int num = PersistTool.getInt(MessageUtil.MESSAGE_UNREADNUM);
			if (num != 0) {
				if (noticeBubble != null) {
					noticeBubble.setText("" + num);
					noticeBubble.show();
				}
			} else {
				WuLog.i(TAG, "无未读消息");
				noticeBubble.hide();
			}
			break;
		default:
			break;
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.fragment1);
		init();
		setUpView();
		try {
			mPromotions.clear();
			List<Promotion> list = GlobalApplication.appDB
					.findAll(Promotion.class);
			if (list != null && list.size() != 0) {
				mPromotions.addAll(list);
			}
			getPromotions();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void setUpView() {
		// 初始化推广布局
		View promotionView = lf.inflate(R.layout.promotion, null);
		// ViewPager滑动页
		mViewPager = (ViewPager) promotionView.findViewById(R.id.viewPager);
		indicator = (CustomIndicator) promotionView
				.findViewById(R.id.indicator);
		mViewPager.setOnPageChangeListener(listener);

		// 设置默认的滑动标题
		mSlideTitle = (TextView) promotionView.findViewById(R.id.tvSlideTitle);
		mLvApps = (ListView) this.findViewById(R.id.lv_apps);
		mLvApps.addHeaderView(promotionView);
		mLvApps.setAdapter(new AppAdapter(TabOneActivity.this, mAppInfos,
				mLvApps));
		mLvApps.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ZnmList znmList = mAppInfos.get(position);
				if ("dianle".equals(znmList.getId())) {
					isLoadPoint = true;
					Dianle.showOffers();
				}
			}
		});
	}

	boolean isLoadPoint;

	private void init() {
		lf = LayoutInflater.from(this);
		JpushUtil.regJush();
		AdUtil.regAd(this);
		getPromotions();
	}

	public List<ZnmList> getZnmlist() {
		ArrayList<ZnmList> list = new ArrayList<ZnmList>();
		ZnmList znmList = new ZnmList();
		znmList.setAppName("赚你妹高速赚妹币通道一");
		znmList.setId("youmi");
		ZnmList znmList1 = new ZnmList();
		znmList1.setAppName("赚你妹高速赚妹币通道二");
		znmList1.setId("dianle");
		list.add(znmList);
		list.add(znmList1);
		return list;
	}

	/**
	 * 获取推广商品的列表
	 */
	private void getPromotions() {
		RequestParams mParams = ZnmHttpParams.getDefaultRequestParams();
		RequestServerData.getAdds(mParams, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String result = responseInfo.result;
				WuLog.i(TAG, "tabOne ->" + result);
				try {
					JSONObject jobj = new JSONObject(result);
					String code = jobj.getString("code");
					if ("0".equals(code)) {
						mPromotions.clear();
						List<Promotion> list = new PromotionParser()
								.parseJSON(result);
						if (list != null && list.size() != 0) {
							mPromotions.addAll(list);
						}
						initViewPager();
					}

				} catch (Exception e) {
					e.printStackTrace();
				}

			}

			@Override
			public void onFailure(HttpException error, String msg) {
				UiUtil.showToast("error<<" + msg);
			}

			@Override
			public void onStart() {
				super.onStart();
			}
		});

	}

	private void initViewPager() {
		LayoutInflater mLi = LayoutInflater.from(this);
		final ArrayList<View> views = new ArrayList<View>();
		indicator.setCount(mPromotions.size());
		// 将要分页显示的View装入数组中
		int i = 0;
		for (final Promotion as : mPromotions) {
			mSlideTitle.setText(mPromotions.get(0).getTitle());
			i++;
			View view1 = mLi.inflate(R.layout.content, null);
			ImageView imageView = (ImageView) view1
					.findViewById(R.id.image_view);
			// imageView.setBackgroundDrawable(TabOneActivity.this.getResources().getDrawable(R.drawable.ic_launcher));
			BitmapUtils bitmapUtils = new BitmapUtils(this);
			bitmapUtils.display(imageView, as.getPicture());
			view1.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (!TextUtils.isEmpty(as.getType())) {
						int type = Integer.parseInt(as.getType());
						Intent intent;
						switch (type) {
						case 1:
							// 1是活动
							intent = new Intent(TabOneActivity.this,
									LotteryDetailActivity.class);
							intent.putExtra(LotteryDetailActivity.SHOP_LUCKID,
									as.getLuckId());
							intent.putExtra(LotteryDetailActivity.SHOP_CYID,
									as.getCgyId());
							intent.putExtra(LotteryDetailActivity.SHOP_PHASE,
									as.getPhase());
							startActivity(intent);
							break;
						case 2:
							// 2是商品
							intent = new Intent(TabOneActivity.this,
									LotteryDetailActivity.class);
							startActivity(intent);
							break;
						}
					}else{
						showCustomToast("type=="+as.getType());
					}

				}
			});
			views.add(view1);
		}

		PagerAdapter mPagerAdapter = new PagerAdapter() {

			@Override
			public boolean isViewFromObject(View arg0, Object arg1) {
				return arg0 == arg1;
			}

			@Override
			public int getCount() {
				return views.size();
			}

			@Override
			public void destroyItem(View container, int position, Object object) {
				((ViewPager) container).removeView(views.get(position));
			}

			@Override
			public Object instantiateItem(View container, int position) {
				((ViewPager) container).addView(views.get(position));
				return views.get(position);
			}
		};
		mViewPager.setAdapter(mPagerAdapter);

	}

	private OnPageChangeListener listener = new OnPageChangeListener() {

		@Override
		public void onPageSelected(int arg0) {
			indicator.setCurrentPosition(arg0);

			String addTopic = mPromotions.get(arg0).getTitle();
			if (!TextUtils.isEmpty(addTopic)) {
				mSlideTitle.setText(addTopic);
			}

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		if (isLoadPoint) {
			Dianle.getTotalMoney(new GetTotalMoneyListener() {

				@Override
				public void getTotalMoneySuccessed(String arg0, long arg1) {
					LogUtils.i(arg0 + "<<" + arg1);
					isLoadPoint = false;
					updatePoint(arg1);
				}

				@Override
				public void getTotalMoneyFailed(String arg0) {

				}
			});
		}
	}

	protected void updatePoint(long arg1) {
		RequestParams mParams = new RequestParams();
		mParams.addBodyParameter("userId", ZnmData.getUserData()
				.getUserUserId());
		mParams.addBodyParameter("channel", "dianle");
		mParams.addBodyParameter("point", arg1 + "");

		RequestServerData.updatePoint(mParams, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String result = responseInfo.result;
				LogUtils.i("result<<" + result);
			}

			@Override
			public void onFailure(HttpException error, String msg) {

			}
		});
	};

	@Override
	protected void onStart() {
		super.onStart();
		mTitlePane.setTitle("赚你妹");
		mTitlePane.getLeftButton().setVisibility(View.VISIBLE);
		if (noticeBubble == null) {
			noticeBubble = new BubbleView(TabOneActivity.this,
					mTitlePane.getLeftButton());
			noticeBubble.setBackgroundResource(R.drawable.lukeying);
			noticeBubble.setBadgePosition(BubbleView.POSITION_TOP_LEFT);
			noticeBubble.setTextSize(12);
			// noticeBubble.setHightAndWidth(noticeBubble.dipToPixels(10),
			// noticeBubble.dipToPixels(10), noticeBubble.dipToPixels(2));
		}

		int num = PersistTool.getInt(MessageUtil.MESSAGE_UNREADNUM);
		if (num != 0) {
			noticeBubble.setText("" + num);
			noticeBubble.show();
		} else {
			WuLog.i(TAG, "无未读消息 onstart");
			noticeBubble.hide();
		}

		mTitlePane.getLeftButton().setText("消息");
		mTitlePane.getLeftButton().setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (noticeBubble != null) {
					noticeBubble.hide();
				}
				PersistTool.saveInt(MessageUtil.MESSAGE_UNREADNUM, 0);
				Intent intent = new Intent(TabOneActivity.this,
						MessageActivity.class);
				startActivity(intent);
			}
		});
	}

}
